package com.it.boot.config.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.it.boot.service.UserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // 每次获取都是新实例
@Component
public class UserImportListener implements ReadListener<UserImportVO> {
    private static final int BATCH_SIZE = 1000;
    private final List<UserImportVO> successList = new ArrayList<>();
    private final List<ImportError> errorList = new ArrayList<>();
    @Resource
    private Validator validator;
    @Resource
    private UserService userService;
    // private static final Validator validator;
    // static {
    //     try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
    //         validator = factory.getValidator();
    //     } // 工厂在这里正确关闭
    // }

    @Override
    public void invoke(UserImportVO data, AnalysisContext context) {
        // 数据校验
        BindingResult bindingResult = new BeanPropertyBindingResult(data, UserImportVO.class.getSimpleName());
        validator.validate(data, bindingResult);

        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                int rowNum = context.readRowHolder().getRowIndex() + 1;
                errorList.add(new ImportError(rowNum, error.getDefaultMessage()));
            });
            return;
        }

        successList.add(data);
        // 达到BATCH_SIZE了，需要存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (successList.size() >= BATCH_SIZE) {
            saveData();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 处理最后一批数据
        saveData();
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行: {}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            Integer rowIndex = excelDataConvertException.getRowIndex();
            Integer columnIndex = excelDataConvertException.getColumnIndex();
            log.error("第{}行，第{}列解析异常", rowIndex, columnIndex);

            errorList.add(new ImportError(rowIndex, exception.getMessage()));
            // 可以在这里记录解析错误的行
        }
    }

    private void saveData() {
        if (successList.isEmpty()) {
            return;
        }
        // 这里实现数据保存逻辑，可以批量插入数据库
        log.info("{}条数据开始存储数据库！", successList.size());
        // userService.saveOrUpdateBatch(successList);
        successList.clear();
    }

    public int getSuccessCount() {
        return successList.size();
    }

    public int getErrorCount() {
        return errorList.size();
    }
}